package com.fly.security.browser;

import com.fly.core.security.properties.SecurityProperties;
import com.fly.core.security.validate.code.ValidateCodeFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

/**
 * Security配置适配器
 */
@Configuration
public class BrowserSecurityConfig extends WebSecurityConfigurerAdapter {
    // 密码加密
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    // 自定义的配置
    @Autowired
    private SecurityProperties securityProperties;

    // 跳转成功
    @Autowired
    private AuthenticationSuccessHandler flyAuthenticationSuccessHandler;

    // 跳转失败
    @Autowired
    private AuthenticationFailureHandler flyAuthenticationFailureHandler;
    //-----------------------记住我------------------------
    @Autowired
    private DataSource dataSource;
    // 用户信息
    @Autowired
    private UserDetailsService userDetailsService;

    // 记住我 的令牌存储
    @Bean
    public PersistentTokenRepository persistentTokenRepository(){
        JdbcTokenRepositoryImpl tokenRepository = new JdbcTokenRepositoryImpl();
        tokenRepository.setDataSource(dataSource);
//        tokenRepository.setCreateTableOnStartup(true); //启动时创建表PERSISTENT_LOGINS 下次启动要注释掉，因为表已存在
        return tokenRepository;
    }
    //-----------------------------------------------
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        ValidateCodeFilter validateCodeFilter = new ValidateCodeFilter();
        validateCodeFilter.setAuthenticationFailureHandler(flyAuthenticationFailureHandler);
        validateCodeFilter.setSecurityProperties(securityProperties);
        validateCodeFilter.afterPropertiesSet();
        http.addFilterBefore(validateCodeFilter, UsernamePasswordAuthenticationFilter.class)//密码验证前先执行验证码过滤
                .formLogin()  //表单方式验证
                .loginPage("/authentication/require")
                .loginProcessingUrl("/authentication/form") // 登录后跳转
                .successHandler(flyAuthenticationSuccessHandler)
                .failureHandler(flyAuthenticationFailureHandler)
                .and()
                .rememberMe()
                .tokenRepository(persistentTokenRepository()) //令牌存储
                .tokenValiditySeconds(securityProperties.getBrowser().getRememberMeSeconds()) //过期时间
                .userDetailsService(userDetailsService)  //用户信息
//        http.httpBasic()// httpBasic 方式验证
                .and()
                .authorizeRequests()
                .antMatchers("/authentication/require",
                        securityProperties.getBrowser().getLoginPage(),
                        "/code/*"  //验证码
                ).permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .csrf().disable();
    }
}
